<template>
 <div>
   <div  class="input-container">
     <!-- 患者信息卡片开始-->
     <div class="box-container flex justify-content-space-between align-center">
       <div>
         <div class="patient-header flex align-center">
           <img src="@/assets/static/用户.png" class="avatar-container" alt="">
           <div class="patient-details">
             <div class="patient-name">{{ groupResult.userName }} (ID: {{ groupResult.userId }})</div>
             <div class="patient-meta">
               <span class="meta-item">{{ groupResult.sex == "Male"? "男" : groupResult.sex == "Woman"?"女":"未知" }} · {{ groupResult.age }}岁</span>
               <span class="meta-item">· 医保类型: {{ groupResult?.bmiInfo?.bmiInfoName }}</span>
             </div>
           </div>
         </div>
         <div class="hospitalization-info">
           <div class="info-row">
             <div class="label">住院号</div>
             <div class="value">{{ groupResult.admNumber }}</div>
           </div>
           <div class="info-row">
             <div class="label">主治医师</div>
             <div class="value">{{ groupResult.doctorName }}</div>
           </div>
           <div class="info-row">
             <div class="label">科室</div>
             <div class="value">{{ groupResult?.departMentInfo?.departMenName }}</div>
           </div>
         </div>
       </div>
       <div class="date-info flex">
         <div class="date-item">
           <div class="date-label">入院日期</div>
           <div class="date-value">{{ groupResult.admTime }}</div>
         </div>
         <div class="date-item">
           <div class="date-label">出院日期</div>
           <div class="date-value">{{ groupResult.outTime }}</div>
         </div>
         <div class="date-item">
           <div class="date-label">住院天数</div>
           <div class="date-value" style="color: #00968F; font-weight: bold;">{{ groupResult.admDay }}天</div>
         </div>
       </div>
     </div>
     <div class="box-container group-result-box" style="margin-top: 20px">
       <div style="font-size: 18px;font-weight: bolder">分组结果</div>
       <div style="font-weight: bolder;font-size:28px;margin-top: 10px;margin-bottom: 10px">{{groupResult.mdcCodeKey?groupResult.mdcCodeKey:"null"}} - {{groupResult.mdcName}}</div>
        <div class="flex  flex-wrap" style="gap: 15px">
          <div style="padding: 20px" class="align-center group-name" v-for="(item,index) in (groupResult.adrgCodeListItems)">
           <div class="flex align-center">
             <div class="name">{{item.diseaseKey}}</div>
             <div style="letter-spacing: 1px">{{item.diseaseName}} </div>
           </div>
            <div class="flex" style="margin-top: 10px">
              <div class="item flex align-center">
                <img src="@/assets/static/DRG类型.png" alt="">
                <div>{{item.unitName?item.unitName:"null"}}</div>
              </div>

              <div class="item flex align-center" style="margin: 0 20px">
                <img src="@/assets/static/MCC.png" alt="" style="">
                <div>{{item.mcCorCCTableName?item.mcCorCCTableName:"null"}}</div>
              </div>

              <div class="item flex align-center">
                <img src="@/assets/static/标准住院日.png" alt="" >
                <div>标准住院日: {{item.standardDay?item.standardDay:0}}天</div>
              </div>
            </div>
          </div>
        </div>
     </div>

     <!-- 患者信息卡片结束-->
     <div class="wrapper flex justify-content-space-between">
       <div class="left-box" style="flex: 1">
         <div class="weight-pay-analysis ">
           <div class="sub-title">权重与支付分析</div>
           <div class="body-box flex justify-content-space-between" style="margin-top: 20px">
             <div class="item flex-auto flex align-center justify-content-center" style="text-align: center;border-right: 4px solid #E5E7EB;height: 160px">
               <div>
                 <div class="val" style="color: #1a8c7b;font-weight: bolder;font-size: 30px">{{groupResult.drgWeight}}</div>
                 <div class="label" style="font-size: 14px">病组权重</div>
               </div>
             </div>
             <div class="item flex-auto flex align-center justify-content-center" style="text-align: center;border-left: 1px solid #edf1f3;border-right: 1px solid #edf1f3;height: 160px">
               <div class="flex justify-content-space-between flex-auto">
                 <div class="flex-auto ">
                   <div class="val" style="color: #000000;font-weight: bolder;font-size: 30px">{{groupResult.diseaseGroupValue}}</div>
                   <div class="label" style="font-size: 14px">病组总点数</div>
                 </div>
                 <div class="flex-auto ">
                   <div class="val" style="color: #000000;font-weight: bolder;font-size: 30px">￥{{groupResult.standardFee}}</div>
                   <div class="label" style="font-size: 14px">桂林年度点值费用</div>
                 </div>
               </div>
             </div>
             <div class="item flex-auto payStyle flex justify-content-center align-center" style="text-align: center;height: 160px">
               <div style="background-color: #FFFFFF ;padding: 5px 50px;border-radius: 5px;">
                 <div class="val" style="color: #1a8c7b;font-weight: bolder;font-size: 30px">￥{{groupResult.expectedFee}}</div>
                 <div class="label" style="font-size: 14px">医保报销金额</div>
               </div>
             </div>
           </div>
         </div>
         <!-- AI开始 -->
         <div style="margin-top: 20px;padding: 20px;background-color: #FFFFFF;border-radius: 10px;">
           <div style="font-weight: bolder;font-size: 18px;color: #333333;margin-bottom: 10px;">人云联拓智能体指导建议</div>
           <div class="flex" style="padding: 20px;" v-if="isAiLoading">
             <div ref="outputRef" class="response-box">
               <!-- 渲染富文本内容 -->
               <div class="ai-response-content" v-html="renderedHTML"></div>
               <!-- 打字光标 -->
               <span v-if="isStreaming" class="cursor">|</span>
             </div>
           </div>
           <aiLoading v-else></aiLoading>
         </div>
         <!--   AI结束 -->
       </div>


     </div>
     <!-- 患者信息卡片结束-->
     <div class="wrapper diagnosis-operation-container flex justify-content-space-between">
       <!-- 主要诊断 -->
       <div class="operation-section flex-auto padding-20" >
         <div class="section-title">诊断结果</div>
         <div class="diagnosis-list">
           <div style="color: #999999;margin-top: 20px">主要诊断</div>
           <div class="diagnosis-item flex align-center">
             <img class="diagnosis-icon" src="@/assets/static/诊断图标.png" alt="">
             <div class="diagnosis-content">
               <div class="diagnosis-code">{{ groupResult.dRGCreateDRGICD10InfoVo.drgOrganizationKey }}</div>
               <div class="diagnosis-name">{{ groupResult.dRGCreateDRGICD10InfoVo.drgOrganizationName }}</div>
             </div>
           </div>
           <div style="color: #999999;margin-top: 20px">其他诊断</div>
           <div v-for="(diagnosis, index) in groupResult.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems" :key="index" class="diagnosis-item flex align-center">
             <img class="diagnosis-icon" src="@/assets/static/诊断图标.png" alt="">
             <div class="diagnosis-content">
               <div class="diagnosis-code">{{ diagnosis.diseaseKey }}</div>
               <div class="diagnosis-name">{{ diagnosis.diseaseName }}</div>
             </div>
           </div>
         </div>
       </div>
       <!-- 手术操作 -->
       <div class="operation-section flex-auto padding-20">
         <div class="section-title">手术操作</div>
         <div class="diagnosis-list">
           <div style="color: #999999;margin-top: 20px">主要手术</div>
           <div class="diagnosis-item flex align-center">
             <img class="diagnosis-icon" src="@/assets/static/手术图标.png" alt="">
             <div class="diagnosis-content">
               <div class="diagnosis-code">{{ groupResult.dRGCreateDRGICD9InfoVo.drgOrganizationKey }}</div>
               <div class="diagnosis-name">{{ groupResult.dRGCreateDRGICD9InfoVo.drgOrganizationName }}</div>
             </div>
           </div>
           <div style="color: #999999;margin-top: 20px">其他手术</div>
           <div v-for="(operation, index) in groupResult.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems" :key="index"  class="diagnosis-item flex align-center">
             <img class="diagnosis-icon" src="@/assets/static/手术图标.png" alt="">
             <div class="diagnosis-content">
               <div class="diagnosis-code">{{ operation.diseaseKey }}</div>
               <div class="diagnosis-name">{{ operation.diseaseName }}</div>
             </div>
           </div>
         </div>
       </div>
     </div>
     <!-- 患者信息卡片结束-->
     <div class="box-container flex justify-content-center" style="margin-top: 20px;padding: 35px 0" >
       <el-button type="primary" @click="saveDRGUserDisease" style="height: 44px">
         <img src="@/assets/static/确认分组.png" style="width: 15px;margin-right: 10px;" alt="">
         <div>保存分组结果</div>
       </el-button>


       <el-button type="primary" plain @click="getUserDetail" style="height: 44px">
         <img src="@/assets/static/重新分组1.png" style="width: 15px;margin-right: 10px;" alt="">
         <div>返回重新分组</div>
       </el-button>

       <el-button type="info" plain @click="resetDRGUserDisease" style="height: 44px">
         <img src="@/assets/static/历史查询.png" style="width: 15px;margin-right: 10px;" alt="">
         <div style="color: #333333">历史查询</div>
       </el-button>

       <el-button type="info" plain @click="exportGroupResult" style="height: 44px">
         <img src="@/assets/static/导出结果.png" style="width: 15px;margin-right: 10px;" alt="">
         <div style="color: #333333">导出分组结果</div>
       </el-button>
     </div>
     <!-- 历史记录弹窗 -->
     <el-dialog v-model="historyDialogVisible" title="患者DRG分组历史记录" width="80%">
       <el-table :data="historyTableData" style="width: 100%">
         <el-table-column prop="userId" label="患者ID" align="center" />
         <el-table-column prop="userName" label="姓名" align="center" />
         <el-table-column prop="admNumber" label="住院号" align="center" />
         <el-table-column prop="admTime" label="入院日期" align="center" />
         <el-table-column prop="drgWeight" label="RW权重" align="center" />
         <el-table-column prop="drgBoolInfo" label="是否有并发症" align="center">
           <template #default="{ row }">
          <span :class="row.drgBoolInfo ? 'has' : 'no'">
            {{ row.drgBoolInfo ? '是' : '否' }}
          </span>
           </template>
         </el-table-column>
         <el-table-column prop="drgOrganizationKey" label="DRG分组" align="center" />
         <el-table-column prop="espCode" label="特殊治疗" align="center" />
         <el-table-column prop="creationTime" label="创建时间" align="center" />
       </el-table>
     </el-dialog>

   </div>
   <div v-if="isLoading">
     <Loading></Loading>
   </div>
 </div>
</template>
<script setup>
import {nextTick, ref,onMounted} from 'vue';
import Loading from '@/components/Loading/index.vue';
import aiLoading from '@/components/aiLoading/index.vue';
const { proxy } = getCurrentInstance();
import EchartsComponent from "@/components/ECharts/index.vue";
import {aiMsgInfoList, getDRGUserDiseaseList, resetDRGUserDiseaseInfo, SaveDRGUserDiseaseInfo} from "@/api/drg/drg.js";
import {useRoute, useRouter} from 'vue-router';
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'
const router = useRouter();
import {ElMessage} from "element-plus";
const guid = ref("");
const isLoading = ref(false);
const groupResult = ref({
  userName:"",
  userId:"",
  sex:"",
  bmiInfo:{
    bmiInfoName:"",
  },
  admNumber:"",
  doctorName:"",
  departMentInfo:{
    departMenName:"",
  },
  admTime:"",
  outTime:"",
  admDay:"",
  mdcCodeKey:"",
  mdcName:"",
  adrgCodeKey:"",
  adrgCodeName:"",
  drgWeight:"",
  yearAvgInfo:"",
  standardFee:"",
  expectedFee:"",
  actualFee:"",
  differenceFee:"",
  differenceRatio:"",
  dRGCreateDRGICD10InfoVo:{
    drgOrganizationKey:"",
    drgOrganizationName:"",
    dRGCreateDRGICD10InfoItems:[
      {diseaseKey:"",diseaseName:""}
    ]
  },
  dRGCreateDRGICD9InfoVo:{
    drgOrganizationKey:"",
    drgOrganizationName:"",
    drgCreateDRGICD9InfoItems:[
      {diseaseKey:"",diseaseName:""}
    ]
  }
});
const chartOption = ref({
  title: {
    show: true,

  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: function (params) {
      return params[0].name + '<br/>' + params[0].seriesName + ': ¥' + params[0].value;
    }
  },
  xAxis: [
    {
      type: 'category',
      data: ['预付款', '实际费用'],
      axisLabel: {
        color: '#666',
        fontSize: 12
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e6e6e6'
        }
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value}',
        color: '#666',
        fontSize: 12
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e6e6e6'
        }
      }
    }
  ],
  // 数据系列
  series: [
    {
      name: '费用',
      type: 'bar',
      barWidth: '40%',
      data: [22750, 28430],
      itemStyle: {
        color: function (params) {
          if (params.dataIndex === 0) {
            return '#00968F';
          } else {
            return '#FF6B6B';
          }
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '¥{c}',
        color: '#333',
        fontSize: 12
      }
    }
  ]
});
const historyTableData = ref([]);
const historyDialogVisible = ref(false);
const route = useRoute();
const isAiLoading = ref(false);
const costItems = ref([
  { name: '手术费用', percent: 45, color: '#1a73e8' },
  { name: '药品费用', percent: 30, color: '#1a73e8' },
  { name: '耗材费用', percent: 15, color: '#f56c6c' },
  { name: '检查费用', percent: 7, color: '#e6a235' },
  { name: '护理费用', percent: 3, color: '#909399' },
  { name: '其他费用', percent: 5, color: '#909399' },
]);
const exportGroupResult = ()=>{
  proxy.$modal.msgError("分组结果导出功能开发中 !");
}
// DRG 分组数据
const drgGroups = ref([
  {
    code: 'FR21',
    description: '冠状动脉粥样硬化性心脏病伴心绞痛',
    weight: '1.82',
    baseRate: 12500,
    multiple: '1.25',
    selected: true
  },
  {
    code: 'FR22',
    description: '冠状动脉粥样硬化性心脏病不伴心绞痛',
    weight: '1.65',
    baseRate: 12500,
    multiple: '1.38',
    selected: false
  },
  {
    code: 'FR23',
    description: '冠状动脉粥样硬化性心脏病伴并发症',
    weight: '2.05',
    baseRate: 12500,
    multiple: '1.12',
    selected: false
  },
  {
    code: 'FR21',
    description: '冠状动脉粥样硬化性心脏病伴心绞痛',
    weight: '1.82',
    baseRate: 12500,
    multiple: '1.25',
    selected: false
  },
  {
    code: 'FR22',
    description: '冠状动脉粥样硬化性心脏病不伴心绞痛',
    weight: '1.65',
    baseRate: 12500,
    multiple: '1.38',
    selected: false
  },
  {
    code: 'FR23',
    description: '冠状动脉粥样硬化性心脏病伴并发症',
    weight: '2.05',
    baseRate: 12500,
    multiple: '1.12',
    selected: false
  },
  {
    code: 'FR21',
    description: '冠状动脉粥样硬化性心脏病伴心绞痛',
    weight: '1.82',
    baseRate: 12500,
    multiple: '1.25',
    selected: false
  },
  {
    code: 'FR22',
    description: '冠状动脉粥样硬化性心脏病不伴心绞痛',
    weight: '1.65',
    baseRate: 12500,
    multiple: '1.38',
    selected: false
  },
  {
    code: 'FR23',
    description: '冠状动脉粥样硬化性心脏病伴并发症',
    weight: '2.05',
    baseRate: 12500,
    multiple: '1.12',
    selected: false
  }
]);
// 选择分组
const selectGroup = (index) => {
  // 取消所有选中状态
  drgGroups.value.forEach(group => {
    group.selected = false;
  });
  // 设置选中状态
  drgGroups.value[index].selected = true;
}
// 确认分组并保存
const saveDRGUserDisease = async () => {
  let result = await SaveDRGUserDiseaseInfo({guid:guid.value});
   if (result.status == 200 && result.data.code == 200){
     ElMessage.success('分组保存成功！');
     await router.push({path: '/drg/statistics'});
   }else {
     ElMessage.error(result.data.msg);
   }
}
// 重新分组并申诉
const getUserDetail =  () => {
   router.push({ path: '/drg/input',query: {id:guid.value}});
}
// 历史查询信息
const resetDRGUserDisease = async () => {
  let result =  await resetDRGUserDiseaseInfo({userId:groupResult.value.userId});
  historyTableData.value = result.data.data;
  historyDialogVisible.value = true;
  console.log("历史查询信息");
}
// 参数截取
const parameterExtract = (data)=>{
  let diagnosisInfo = "主要诊断:" + data.dRGCreateDRGICD10InfoVo.drgOrganizationName;   // 诊断信息
  let surgeryInfo = "主要手术:" + data.dRGCreateDRGICD9InfoVo.drgOrganizationName; // 手术信息
  data.dRGCreateDRGICD10InfoVo.dRGCreateDRGICD10InfoItems.forEach(item => {
      diagnosisInfo += (",其他诊断:"+item.diseaseName);
  });
  data.dRGCreateDRGICD9InfoVo.drgCreateDRGICD9InfoItems.forEach(item => {
     surgeryInfo += (",其他手术:"+item.diseaseName);
  });
  return (diagnosisInfo + "," +surgeryInfo);
}
// 获取分组结果
const getUserDiseaseDetail = async (id) => {
  if (id == ''){
    ElMessage.error('分组Id不能为空！');
    return false;
  }
  isLoading.value = true;
  try {
    let result =  await getDRGUserDiseaseList({guid:id});
    isLoading.value = false;
    groupResult.value = result.data.data;
    chartOption.value.series[0].data = [ groupResult.value.expectedFee,groupResult.value.actualFee];
    const param = parameterExtract(result.data.data);  // 构建AI接口参数
    console.log("构建AI接口数据",param);
    isAiLoading.value = false;
    await startStream("低风险组病例死亡率：0.8%，手术患者并发症发生率：3.5%，1类切口手术部位感染率：1.2%，平均住院日：6.8天，重返率：2.1%，出院患者手术占比：42%，抗菌药物使用强度：45.6 DDDs，检验和病理阳性率：78%，大型设备检查阳性率：68%，全院医疗质量安全不良事件（AE）发生率：2.8%，全院医院感染（HAI）发生率：1.5%，全院住院患者死亡率：0.9%。")
  }catch (e) {
    isLoading.value = false;
  }finally{
    isLoading.value = false;
  }
}

// ==================== 配置区 ====================
//const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/A/compatible-mode/v1/responses'
// 基础 URL
//const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/9c8cdc23a81e48cc9979e9543ac06c4f/compatible-mode/v1/responses'
const API_URL = 'https://dashscope.aliyuncs.com/api/v2/apps/agent/a6248bff9b9c4f0d819bc0e90adb3629/compatible-mode/v1/responses'
//console.log('selectedApi :'+ selectedApi.value)
const API_KEY = 'sk-69a5314907eb4feea7c1a371c6778a51' // ⚠️ 替换为你自己的有效 Key
// ==================== 响应式数据 ====================
const isStreaming = ref(false)
const renderedHTML = ref('')
const outputRef = ref(null)
// ==================== 初始化 markdown-it（含表格修复插件）====================
const md = new MarkdownIt({
  html: false,
  breaks: true,
  typographer: true
})
// 🔧 插件：检测并转换“空格分隔”的纯文本表格为 Markdown 表格
function detectAndConvertTextTable(text) {
  const lines = text.trim().split('\n')
  let headers = []
  let rows = []

  for (const line of lines) {
    const trimmed = line.trim()
    if (!trimmed) continue

    // 使用多个空格或制表符分割
    const cells = trimmed.split(/\s{2,}|\t/).filter(Boolean)
    if (cells.length < 2) continue // 至少两列

    // 判断是否为表头：不含明显数字/百分比
    const hasNumbers = /[\d\.]+%?/.test(trimmed)
    if (!headers.length && !hasNumbers) {
      headers = cells
    } else if (hasNumbers && cells.length >= headers.length) {
      // 数据行：补全或截断以匹配表头长度
      const row = cells.slice(0, headers.length)
      rows.push(row)
    }
  }

  // 构造 Markdown 表格
  if (headers.length >= 2 && rows.length >= 1) {
    const headerRow = '| ' + headers.join(' | ') + ' |'
    const separatorRow = '| ' + headers.map(() => '---').join(' | ') + ' |'
    const dataRows = rows.map(row => '| ' + row.join(' | ') + ' |').join('\n')
    return [headerRow, separatorRow, dataRows].join('\n')
  }

  return null
}
// ✅ 增强 render 方法：自动修复文本表格
const originalRender = md.render.bind(md)
md.render = function (content) {
  let enhancedContent = content

  // 查找可能的表格块（连续多行，每行有多个空格）
  const potentialBlocks = enhancedContent.match(/(?:^|\n)(?:[^\n]+\s+[^\n]+\n?)+/g)
  if (potentialBlocks) {
    potentialBlocks.forEach(block => {
      const cleanedBlock = block.trim()
      if (!cleanedBlock || cleanedBlock.startsWith('|') || cleanedBlock.includes('---')) return

      const tableMarkdown = detectAndConvertTextTable(cleanedBlock)
      if (tableMarkdown) {
        enhancedContent = enhancedContent.replace(cleanedBlock, tableMarkdown)
      }
    })
  }

  try {
    return originalRender(enhancedContent)
  } catch (e) {
    console.error('[Markdown] 渲染失败:', e)
    return `<p style="color:red">❌ 内容渲染错误</p>`
  }
}
// ==================== 流式请求 ====================
const startStream = async (aiParam) => {
  if (isStreaming.value) return
  renderedHTML.value = ''
  isStreaming.value = true
  let accumulatedText = ''
  try {
    const payload = {
      input: [
        {
          type: 'message',
          role: 'user',
          content: [
            {
              type: 'input_text',
              text: aiParam
            }
          ]
        }
      ],
      stream: true
    }
    console.log('API_URL :'+ API_URL)
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(payload)
    })

    if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''
    isAiLoading.value = true;
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop()
      for (const line of lines) {
        const trimmed = line.trim()
        if (!trimmed.startsWith('data:')) continue

        const dataStr = trimmed.slice(5).trim()
        if (!dataStr || dataStr === '[DONE]') continue

        try {
          const data = JSON.parse(dataStr)
          if (data.type === 'response.output_text.delta' && typeof data.delta === 'string') {
            const deltaText = data.delta.replace(/<br>/g, '')
            accumulatedText += deltaText

            // 使用增强版 markdown-it 渲染（含表格修复）
            const unsafeHtml = md.render(accumulatedText)
            renderedHTML.value = DOMPurify.sanitize(unsafeHtml)

            // 自动滚动到底部
            await nextTick()
            outputRef.value?.scrollTo?.(0, outputRef.value.scrollHeight)
          }
        } catch (err) {
          console.warn('[解析失败]', err, dataStr)
        }
      }
    }
    // 结束标记
    const finalText = accumulatedText + '\n\n✅ 报告生成完成。'
    const unsafeHtml = md.render(finalText)
    renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
  } catch (error) {
    console.error('[请求失败]', error)
    renderedHTML.value = `<span style="color:red">❌ 请求失败：${error.message}</span>`
  } finally {
    isStreaming.value = false

  }
}



onMounted(() => {
  guid.value = route.query.id;
  getUserDiseaseDetail( guid.value)
})

</script>
<style lang='scss' scoped>
.input-container {
  padding: 20px;
  border-radius: 5px;
  .box-container {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
  }
  .patient-header {
    .avatar-container {
      width: 40px;
      height: 40px;
      margin-right: 10px;
      border-radius: 50%;
    }

    .patient-name {
      font-weight: 600;
      font-size: 18px;
      color: #333333;
    }

    .patient-meta {
      padding-top: 5px;
      color: #999999;
    }
  }
  .hospitalization-info {
    display: flex;
    margin-top: 20px;

    .info-row {
      padding-right: 20px;
      text-align: start;

      .label {
        color: #999999;
      }
    }
  }
  .date-info {
    .date-item {
      width: 190px;
      text-align: center;

      .date-label {
        color: #999999;
      }

      .date-value {
        color: #000000;
      }
    }
  }
  .wrapper {
    margin-top: 20px;
  }
  .weight-pay-analysis {
    background-color: #ffffff;
    padding: 40px 20px;
    border-radius: 5px;
    .sub-title {
      font-weight: bolder;
      font-size: 18px;
      color: #333333;
    }

    .item {
      .label {
        color: #7c7676;
        font-size: 16px;
      }
    }

    .sign-card {
      margin-top: 20px;
      position: relative;
      background-color: #FFFFFF;
      padding: 40px 20px;
      border-radius: 5px;
      /* 自定义文字容器样式 */
      .progress-text {
        position: absolute;
        color: #333;
        display: flex;
        justify-content: space-between;
        width: 100%;
      }

      .percent-text {
        font-size: 14px;
        text-align: end;
      }

      :deep(.el-progress-bar__inner) {
        background-color: #1a8c7b !important;
      }

      :deep(.el-progress) {
        display: block;
      }

      .sign-info {
        font-size: 12px;
      }
    }
  }
  .pay-info-container {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
    .sub-title {
      font-weight: bolder;
      font-size: 18px;
      color: #333333;
    }
    .pay-info {
      margin-top: 20px;

      .date-item {
        margin-right: 80px;

        .date-label {
          margin-bottom: 10px;
          color: #999999;
        }

        .date-value {
          font-size: 18px;
        }
      }
    }
    .chart-container {
      margin-top: 17px;
      .charts-common {
        height: 300px;
      }
    }
  }
}
.alert-warning-container {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e6f7ff;
  .sub-title {
    font-size: 18px;
    font-weight: bolder;
  }
  .alert-list{
      height: 155px;
     overflow-y: auto;
     .alert-item {
       display: flex;
       align-items: center;
       padding: 12px 0;
       border-bottom: 1px dashed #e6f7ff;

       .alert-icon {
         width: 40px;
         height: 40px;
         margin-right: 10px;
         border-radius: 50%;
         display: block;

       }

       .alert-content {
         flex: 1;

         .alert-title {
           font-size: 16px;
           font-weight: bold;
           color: #333;
           margin-bottom: 5px;
         }
       }
     }
   }
}
.drg-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 20px;
  height: 380px;
  overflow-y: auto;
  .drg-item {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: 1px solid #e6f7ff;
  }

  .drg-item:hover {
    background-color: #e6f7ff;
    transform: translateY(-1px);
  }

  .drg-item.selected {
    border-color: #00968F;
    background-color: #f0f8ff;
  }

  .group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .group-code {
    font-size: 16px;
    color: #333;
    font-weight: bolder;
  }

  .group-status {
    background-color: #00968F;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .status-text {
    font-size: 12px;
  }

  .group-description {
    font-size: 16px;
    color: #666;
    margin-bottom: 8px;
  }

  .group-details {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
  }

  .detail-item {
    flex: 1;
    min-width: 120px;
    font-size: 12px;
  }

  .detail-label {
    color: #333;
    font-size: 16px;
    font-weight: 600;
  }

  .detail-value {
    color: #333;
    font-weight: 600;
    font-size: 16px;
  }
}
.diagnosis-operation-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  .operation-section{
     background-color: #FFFFFF;
     border-radius: 10px;
    .section-title{
       font-size: 20px;
       font-weight: bolder;
       color: #333333;
    }
    .diagnosis-item{
      margin-top: 20px;
      .diagnosis-icon{
        width: 40px;
        height: 40px;
        margin-right: 20px;
        border-radius: 50%;
        background-color: rgba(26, 140, 123, 0.21);
      }
      .diagnosis-code{
        font-weight: bolder;
        font-size: 18px;
      }
      .diagnosis-name{
        color: #666666;

      }
    }


  }
}
.group-result-box{
   background-color: transparent !important;
   background: url("../../../assets/static/分组结果背景.png") no-repeat center center;
   background-size: 100% 100%;
   borerder-radius: 10px !important;
   width: 100%;
  .group-name{
     background-color: rgba(102, 102, 102, 0.77);
     border-radius: 10px;
     width: fit-content;
     padding:10px 20px;
    .name{
     font-weight: bolder;
      font-size: 24px;
       margin-right: 10px;
    }
  }
  .item{
      img{
        margin-right: 5px;
        width: 30px;
        display: block;
        background-color: rgba(26, 140, 123, 0.21);
        border-radius: 50%;
      }
  }
}
/* 通用iframe样式 */
.section-iframe {
  width: 100%;
  border: 1px solid #ccc;
  min-height: 100px; /* 初始最小高度 */
}
.payStyle{
  background: url("../../../assets/static/img.png") no-repeat center center;
  background-size: cover ;
  borerder-radius: 10px !important;
}
// =========

.response-box {
  width: 100%;
  padding: 16px;
  overflow-y: auto;
  line-height: 1.7;
  font-size: 15px;
  background-color: #ffffff;
  color: #333333;
}

/* ==================== 富文本样式 ==================== */
.ai-response-content h1,
.ai-response-content h2,
.ai-response-content h3 {
  margin: 1em 0 0.5em;
  color: #07173b;
}
.ai-response-content h1 {
  font-size: 1.8em;
  text-align: center;
}
.ai-response-content h2 {
  font-size: 1.5em;
  border-left: 4px solid #007bff;
  padding-left: 12px;
}
.ai-response-content h3 {
  font-size: 1.3em;
  color: #34495e;
}
:global(.ai-response-content table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  font-size: 0.95em;
  border: 1px solid #2c2a2a;
}
:global(.ai-response-content th,
.ai-response-content td ){
  border: 1px solid #ccc;
  padding: 8px 12px;
  text-align: center;
}
:global(.ai-response-content th ){
  background-color: #f0f5ff;
  font-weight: 600;
  color: #1a3b6d;
}
:global(.ai-response-content tr:nth-child(even) ){
  background-color: #f9f9f9;
}
:global(.ai-response-content p){
  margin: 0.6em 2;
}
:global(.ai-response-content ul) {
  margin-left: 40px;
  margin: 0.6em 1;
  padding-left: 1;
}
:global(.ai-response-content ol) {
  margin-left: 40px;
  margin: 0.6em 2;
  padding-left: 2;
}
:global(.ai-response-content li ){
  margin: 0.6em 1.2;
  padding-left: 20px;
}
.cursor {
  animation: blink 1.2s step-end infinite;
  color: #007bff;
  font-weight: bold;
  font-size: 1.1em;
}
:global(.ai-message table ){
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  font-size: 0.95em;
}
:global(.ai-message th,
.ai-message td ){
  border: 1px solid #ccc;
  padding: 6px 10px;
  text-align: left;
}
:global(.ai-message th ){
  background-color: #f0f5ff;
  font-weight: 600;
}
:global(.ai-message tr:nth-child(even) ){
  background-color: #f9f9f9;
}
@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}






</style>
